package com.ruoyi.project.secret.controller;

import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.secret.domain.SecretResult;
import com.ruoyi.project.secret.service.SecretServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
public class SecretController {
    @Autowired
    private SecretServer secretServer;

    @PostMapping("/authorization")
    public AjaxResult pushSecret(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("请上传文件");
        }
        if (!Objects.requireNonNull(file.getOriginalFilename()).endsWith(".lic")) {
            return AjaxResult.error("上传了错误的文件 请上传.lic文件");
        }
        try {
            InputStream inputStream = file.getInputStream();
            String keyCode = "";
            try {
                int byteOne = 0;
                List<Byte> bytes = new ArrayList<>();
                while ((byteOne = inputStream.read()) != -1) {
                    bytes.add((byte) byteOne);
                }
                byte[] bs = new byte[bytes.size()];
                for (int i = 0; i < bytes.size(); i++) {
                    bs[i] = bytes.get(i);
                }
                keyCode = new String(bs);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("无法解析的lic文件");
            } finally {
                inputStream.close();
            }
            SecretResult secretResult = secretServer.pushCode(keyCode);
            return secretResult.isSuccess() ?
                    AjaxResult.success()
                    : AjaxResult.error(secretResult.getCode(), secretResult.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("文件读取失败");
        }
    }

    @GetMapping("/getSecretTime")
    public AjaxResult getSecret() {
        return AjaxResult.success(secretServer.leftTime());
    }
}
